#!/usr/bin/env python

import picture_source
import logging
import time
import datetime
import procs
import procs.pil
import sys
import os
import os.path

thismodule = sys.modules[__name__]

def create(xconfig, name):
   if name[:3] == "pil":
      obj = getattr(procs.pil, name)
   else:
      obj = getattr(thismodule, name)

   return obj(xconfig)

class sleep(procs.null_processor):
   def __init__(self, xconfig):
      procs.null_processor.__init__(self, xconfig)
      self.sleep_interval = self.config.GetInterval('intervals/frame')
      
   def process(self, data, ts, state):
      logging.debug("Sleep %ss" % self.sleep_interval)
      time.sleep(self.sleep_interval)
      ts = datetime.datetime.now()
      return (data, ts, state)

class frame_start(procs.null_processor):
   def process(self, data, ts, state):
      logging.info("Frame Capture Started")
      return (data, ts, state)

class archive_start(procs.null_processor):
   def process(self, data, ts, state):
      logging.info("Archiving Started")
      return (data, ts, state)

class archiver(procs.null_processor):
   def __init__(self, xconfig):
      procs.null_processor.__init__(self, xconfig)
      self.frame_dir = os.path.abspath(self.config['directories/frame'])
      self.movie_dir = os.path.abspath(self.config['directories/rollup'])

   def process(self, data, ts, state):
      logging.debug("Archive Rollup Started")
      cmd = "mencoder mf://%s/*.jpg -mf fps=10:type=jpg -ovc lavc -ffourcc DX50 -o %s.avi"
      cmd = cmd % (
                   self.frame_dir,
                   os.path.join(self.movie_dir, ts.strftime("%Y%j-%H")),
                  )
      logging.debug(cmd)
      os.system("%s > /dev/null" % cmd)
      return (data, ts, state)

class clean_frames(procs.null_processor):
   def __init__(self, xconfig):
      procs.null_processor.__init__(self, xconfig)
      self.frame_dir = os.path.abspath(self.config['directories/frame'])

   def process(self, data, ts, state):
      dir = os.listdir(self.frame_dir)
      for file in dir:
         os.unlink(os.path.join(self.frame_dir, file))
      return (data, ts, state)

class source(procs.null_processor):
   def __init__(self, xconfig):
      procs.null_processor.__init__(self, xconfig)
      self.source = picture_source.create(self.config)

   def process(self, data, ts, state):
      logging.debug("GetImage")
      return (self.source.get_picture(), ts, state)
